open Printf
open ExtLib
open Common

module MoviesMap = Map.Make(Int64)
	
class moviesCollection () = object(self)
	val _dataAccessor = new MoviesDal.movies_dal "test.db"
	val mutable _data = MoviesMap.empty

	(* events *)
	val _on_add : (MoviesDal.movie -> unit) Events.event = new Events.event()
	val _on_remove : (MoviesDal.movie -> unit) Events.event = new Events.event()
	
		
	initializer
		_data <- List.fold_right
			(fun m map -> MoviesMap.add m#id m map)
			(_dataAccessor#load_movies())
			MoviesMap.empty

	method items =
		MoviesMap.fold (fun _ m col -> (m :> MovieDto.movie) :: col) _data []

	method item id =
		let res = MoviesMap.find id _data in
			(res :> MovieDto.movie)

	method add_movie (m : MovieDto.movie) =
		let newMovie = _dataAccessor#add_movie m#title m#year m#desc in
			_data <- MoviesMap.add newMovie#id newMovie _data;
			_on_add#emit (Events.emtr newMovie)

	method remove_movie id =
		let movieToRemove = MoviesMap.find id _data in
			_on_remove#emit (Events.emtr movieToRemove);
			_data <- MoviesMap.remove id _data;
			_dataAccessor#delete_movie movieToRemove
				
	(* events *)
	method on_add = (_on_add :> (MovieDto.movie -> unit) Events.eventItf)
	method on_remove = (_on_remove :> (MovieDto.movie -> unit) Events.eventItf)
end
